﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Forms;
using AntDesign;
using Vditor;
using Vditor.Models;
using PhotinoNote.Entities;
using PhotinoNote.Dtos;
using Microsoft.EntityFrameworkCore;

namespace PhotinoNote
{
    public partial class App
    {

        [Inject]
        IMessageService MessageBox { get; set; }
        [Inject]
        ModalService ModalService { get; set; }



        ApplicationDbContext db = new ApplicationDbContext();


        // 笔记本列表
        List<NotebookDto> notebookList = new List<NotebookDto>();
        // 笔记列表
        List<NoteDto> noteList = new List<NoteDto>();
        // 当前选中笔记本
        string currentNotebookId = null;
        // 当前选中笔记
        string currentNoteId = null;
        string[] selectedNoteKeys = { };
        // 文章标题
        string artTitle = "";
        // 文章Markdown内容
        string artMdContent = "";
        // 文章html内容
        string artHtmlContent = "";
        // 编辑器是否显示
        bool editorIsShow = false;
        // 编辑器对象
        Editor editor;
        // 编辑器工具条
        Toolbar editorToolbar = new Toolbar();
        // 编辑器上传配置
        //Vditor.Models.Upload upload = new Vditor.Models.Upload()
        //    {
        //        Url = "api/upload",
        //        Max = 2 * 1024 * 1024,
        //        Accept = "image/*",
        //        Multiple = false,
        //    };

        // 添加笔记本表单模型
        Form<NotebookFroCreateDto> _addNotebookForm;
        // 添加笔记本表单绑定的模型具体类
        NotebookFroCreateDto addNotebookModel = new NotebookFroCreateDto();
        // 添加笔记本表单是否显示
        bool addNotebookIsShow = false;
        // 加载状态
        bool addNotebookloading = false;


        /// <summary>
        /// 笔记本被选中
        /// </summary>
        /// <param name="item"></param>
        void OnNotebookClick(MenuItem item)
        {
            currentNotebookId = item.Key;
            selectedNoteKeys = new string[] { };
            noteList.Clear();
            currentNoteId = null;
            artTitle = "";
            artMdContent = "";
            artHtmlContent = "";
            var tempNotes = db.Notes.Where(x => x.NotebookId.ToString() == item.Key).ToList();
            tempNotes.ForEach(x =>
            {
                noteList.Add(new NoteDto(x.Id, x.Title));
            });
        }

        /// <summary>
        /// 显示添加笔记本弹窗
        /// </summary>
        void ShowAddNotebookModal()
        {
            addNotebookIsShow = true;
        }

        /// <summary>
        /// 提交提交笔记本
        /// </summary>
        /// <param name="e"></param>
        void HandleAddNotebookOk(MouseEventArgs e)
        {
            var res = _addNotebookForm.Validate();
            if (!res) return;
            addNotebookloading = true;
            _addNotebookForm.Submit();
        }



        /// <summary>
        /// 取消提交笔记本
        /// </summary>
        /// <param name="e"></param>
        void HandleAddNotebookCancel(MouseEventArgs e)
        {
            _addNotebookForm.Reset();
            addNotebookIsShow = false;
        }

        /// <summary>
        /// 确认添加笔记本
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        async Task HandAddNotebookOnFinish(EditContext context)
        {
            // 判断笔记本是否存在，存在则不再添加
            var isExit = db.Notebooks.Where(x => x.Name.ToLower() == addNotebookModel.Name.ToLower())
                        .FirstOrDefault();
            if (isExit != null)
            {
                await MessageBox.Info("笔记本已存在!");
                return;
            }

            // 添加逻辑
            var notebook = new Notebook();
            notebook.Name = addNotebookModel.Name;
            notebook.CreateAt = DateTime.Now;
            await db.Notebooks.AddAsync(notebook);
            int res = db.SaveChanges();
            if (res > 0)
            {
                _addNotebookForm.Reset();
                addNotebookIsShow = false;
                LoadNotebookListData();
            }
            else
            {
                await MessageBox.Error("操作失败!");
            }
            addNotebookloading = false;
        }



        /// <summary>
        /// 处理添加笔记本失败
        /// </summary>
        /// <param name="editContext"></param>
        /// <returns></returns>
        async Task HandAddNotebookOnFinishFailed(EditContext editContext)
        {
            _addNotebookForm.Reset();
            await MessageBox.Error($"Failed:{JsonSerializer.Serialize(addNotebookModel)}");
        }


        /// <summary>
        /// 删除笔记本
        /// </summary>
        /// <returns></returns>
        async Task ShowRemoveNotebookModal()
        {
            if (string.IsNullOrEmpty(currentNotebookId))
            {
                await MessageBox.Warning("请选择笔记本！", 1);
                return;
            }
            var notebook = db.Notebooks.FirstOrDefault(x => x.Id.ToString() == currentNotebookId);
            if (notebook == null) return;
            await ModalService.ConfirmAsync(new ConfirmOptions()
            {
                Title = "提示",
                Icon = deleteConfirmIcon,
                Content = $"确定删除笔记本 `{notebook.Name}` 吗？",
                OnOk = (e) =>
                {
                    // 删除逻辑
                    db.Notebooks.Remove(notebook);
                    int res = db.SaveChanges();
                    currentNotebookId = null;
                    return Task.CompletedTask;
                },
                OnCancel = (e) => Task.CompletedTask,
                OkType = "danger",
            });

            // 重新加载数据
            LoadNotebookListData();
        }



        /// <summary>
        /// 笔记被选中
        /// </summary>
        /// <param name="item"></param>
        void OnNoteClick(MenuItem item)
        {
            editorIsShow = true;
            currentNoteId = item.Key;
            selectedNoteKeys = new string[] { item.Key };
            artMdContent = string.Empty;

            // 判断临时笔记
            if (Regex.IsMatch(item.Key, @"[0-9]{14}"))
            {
                artTitle = item.Key;
                artMdContent = "";
                return;
            }

            var note = db.Notes.Where(x => x.Id.ToString() == currentNoteId).FirstOrDefault();
            if (note == null) return;
            artTitle = note.Title;
            artMdContent = note.Content;
        }


        /// <summary>
        /// 新建临时笔记
        /// </summary>
        async void AddNote()
        {
            if (string.IsNullOrEmpty(currentNotebookId))
            {
                await MessageBox.Warning("请选择笔记本再操作！");
                return;
            }
            selectedNoteKeys = new string[] { };
            editorIsShow = true;
            string title = DateTime.Now.ToString("yyyyMMddHHmmss");
            long tempId = long.Parse(title);
            //noteList.Add(new NoteDto(tempId, title, ""));
            noteList.Insert(0, new NoteDto(tempId, title, ""));
            artTitle = title;
            artMdContent = "";
            artHtmlContent = "";
            selectedNoteKeys = new string[] { title };
            currentNoteId = title;
        }

        /// <summary>
        /// 删除笔记
        /// </summary>
        async Task RemoveNote()
        {
            if (string.IsNullOrEmpty(currentNotebookId))
            {
                await MessageBox.Warning("请选择笔记本！", 1);
                return;
            }
            if (string.IsNullOrEmpty(currentNoteId))
            {
                await MessageBox.Warning("请选择笔记！", 1);
                return;
            }

            // 判断临时笔记
            if (Regex.IsMatch(currentNoteId, @"[0-9]{14}"))
            {
                noteList.RemoveAll(x => x.Id.ToString() == currentNoteId);
                currentNoteId = null;
                selectedNoteKeys = new string[] { };
                artTitle = "";
                artMdContent = "";
                artHtmlContent = "";
                return;
            }

            var notebook = db.Notebooks.Include(x => x.Notes).FirstOrDefault(x => x.Id.ToString() == currentNotebookId);
            if (notebook == null) return;
            var note = notebook.Notes.Where(x => x.Id.ToString() == currentNoteId).FirstOrDefault();
            if (note == null) return;
            await ModalService.ConfirmAsync(new ConfirmOptions()
            {
                Title = "提示",
                Icon = deleteConfirmIcon,
                Content = $"确定删除笔记 `{note.Title}` 吗？",
                OnOk = (e) =>
                {
                    // 删除逻辑
                    notebook.Notes.Remove(note);
                    int res = db.SaveChanges();
                    currentNoteId = null;
                    selectedNoteKeys = new string[] { };
                    artTitle = "";
                    artMdContent = "";
                    artHtmlContent = "";
                    return Task.CompletedTask;
                },
                OnCancel = (e) => Task.CompletedTask,
                OkType = "danger",
            });

            // 重新加载数据
            LoadNoteListData();
        }





        /// <summary>
        /// 加载笔记本列表数据
        /// </summary>
        void LoadNotebookListData()
        {
            notebookList.Clear();
            var tempNotebooks = db.Notebooks.AsNoTracking().OrderBy(x => x.Id).ToList();
            tempNotebooks.ForEach(x =>
            {
                notebookList.Add(new NotebookDto(x.Id, x.Name));
            });
        }



        /// <summary>
        /// 加载笔记数据
        /// </summary>
        void LoadNoteListData()
        {
            selectedNoteKeys = new string[] { };
            noteList.Clear();
            currentNoteId = null;
            artTitle = "";
            artMdContent = "";
            artHtmlContent = "";
            var tempNotes = db.Notes.AsNoTracking()
                .Where(x => x.NotebookId.ToString() == currentNotebookId).ToList();
            tempNotes.ForEach(x =>
            {
                noteList.Add(new NoteDto(x.Id, x.Title));
            });
        }


        /// <summary>
        /// 生命周期，初始化
        /// </summary>
        protected override void OnInitialized()
        {
            currentNotebookId = null;
            currentNoteId = null;
            selectedNoteKeys = new string[] { };

            LoadNotebookListData();

            string[] keys = { "emoji",
"headings",
"bold",
"italic",
"strike",
"link",
"|",
"list",
"ordered-list",
"check",
"outdent",
"indent",
"|",
"quote",
"line",
"code",
"inline-code",
"insert-before",
"insert-after",
"|"};
            editorToolbar.Buttons.AddRange(keys.ToList());

            // 自定义Toolbar按钮
            CustomToolButton toolbar = new CustomToolButton()
            {
                ClassName = "saveart",
                //Hotkey = "⌘-⇧-S",
                Hotkey = "⌘S",
                //Icon = "<svg><use xlink:href=\"#vditor-icon-export\"></use></svg>",
                Icon = @"<svg t='1681650341296' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg'
p-id='2861' width='200' height='200'><path d='M704 128l192 192v512a64 64 0 0 1-64 64H192a64 64 0 0 1-64-64V192a64 64 0 0
1 64-64h512z m-64 64H384v96h256V192z m64 26.496V352H320V192H192v640h128V512h384v320h128V346.496l-128-128zM640
832V576H384v256h256z' p-id='2862'></path></svg>",
                Name = "save",
                //Tip = "自定义Toolbar",
                Tip = "保存文章",
                TipPosition = "n"
            };

            //editorToolbar.Buttons.Add(toolbar);
            editorToolbar.Buttons.Insert(0, toolbar);   // 自定义按钮放到最前面

            string[] keys2 = {"upload",
"record",
"table",
"|",
"undo",
"redo",
"|",
"fullscreen"};
            editorToolbar.Buttons.AddRange(keys2.ToList());


            base.OnInitialized();
        }


        /// <summary>
        /// 文章标题内容校验
        /// </summary>
        /// <returns></returns>
        async Task ArtTitleOnBlur()
        {
            if (string.IsNullOrEmpty(artTitle))
            {
                await MessageBox.Warning("请输入文章标题！");
                return;
            }
            if (artTitle.Length >= 255)
            {
                await MessageBox.Warning("标题长度不超255字符！");
                return;
            }
            //if (Regex.IsMatch(artTitle, @"^\d+$"))
            //{
            //    await MessageBox.Warning("请输入正确的文章标题！");
            //    return;
            //}
        }


        /// <summary>
        /// 自定义保存按钮被点击
        /// </summary>
        /// <param name="name"></param>
        async Task OnToolbarButtonClick(string name)
        {
            if (string.IsNullOrEmpty(artTitle) || string.IsNullOrEmpty(artMdContent))
            {
                await MessageBox.Warning("请输入文章标题和内容！");
                return;
            }
            if (Regex.IsMatch(artTitle, @"^\d+$"))
            {
                await MessageBox.Warning("请输入正确的文章标题！");
                return;
            }

            // 判断笔记是否存在，存在则更新
            var note = db.Notes.Where(x => x.Id.ToString() == currentNoteId).FirstOrDefault();
            if (note != null)
            {
                note.Title = artTitle;
                note.Content = artMdContent;
                note.UpdateAt = DateTime.Now;
                db.SaveChanges();
                await MessageBox.Success("更新成功！");
                LoadNoteListData();
                return;
            }

            // 不存在则添加
            var notebook = db.Notebooks.Include(x => x.Notes).Where(x => x.Id.ToString() == currentNotebookId)
                .FirstOrDefault();
            notebook.Notes.Add(new Note(artTitle, artMdContent, DateTime.Now));
            int res = db.SaveChanges();
            if (res > 0)
            {
                await MessageBox.Success("新增成功！");
                LoadNoteListData();
                return;
            }
            await MessageBox.Error("新增失败！");
        }


    }
}
